<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="loadload 会在类装载的时候调用（main函数执行之前）。load 不会被覆盖，如果父类、父类分类、子类、子类分类，同时实现了 load 方法，那么这些方法都会执行。 调用顺序1、先调用父类的 load 方法，再调用子类的 load 方法。2、先调用本类的 load 方法，再调用分类的 load 方法。 使用场景1、Method Swizzle 。 initializeinitialize">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS开发之理解load和initialize">
<meta property="og:url" content="https://vhuichen.github.io/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%90%86%E8%A7%A3load%E5%92%8Cinitialize/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="loadload 会在类装载的时候调用（main函数执行之前）。load 不会被覆盖，如果父类、父类分类、子类、子类分类，同时实现了 load 方法，那么这些方法都会执行。 调用顺序1、先调用父类的 load 方法，再调用子类的 load 方法。2、先调用本类的 load 方法，再调用分类的 load 方法。 使用场景1、Method Swizzle 。 initializeinitialize">
<meta property="og:locale">
<meta property="og:image" content="http://ovsbvt5li.bkt.clouddn.com/18-4-11/38950580.jpg">
<meta property="article:published_time" content="2018-04-09T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-01T08:13:16.818Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="load">
<meta property="article:tag" content="initialize">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ovsbvt5li.bkt.clouddn.com/18-4-11/38950580.jpg">


<link rel="canonical" href="https://vhuichen.github.io/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%90%86%E8%A7%A3load%E5%92%8Cinitialize/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%90%86%E8%A7%A3load%E5%92%8Cinitialize/","path":"2018/04/2018/04/iOS开发之理解load和initialize/","title":"iOS开发之理解load和initialize"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>iOS开发之理解load和initialize | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#load"><span class="nav-number">1.</span> <span class="nav-text">load</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B0%83%E7%94%A8%E9%A1%BA%E5%BA%8F"><span class="nav-number">1.1.</span> <span class="nav-text">调用顺序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-number">1.2.</span> <span class="nav-text">使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#initialize"><span class="nav-number">2.</span> <span class="nav-text">initialize</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B0%83%E7%94%A8%E9%A1%BA%E5%BA%8F-1"><span class="nav-number">2.1.</span> <span class="nav-text">调用顺序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8"><span class="nav-number">2.2.</span> <span class="nav-text">线程安全</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%97%AE%E9%A2%98"><span class="nav-number">2.3.</span> <span class="nav-text">问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF-1"><span class="nav-number">2.4.</span> <span class="nav-text">使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F"><span class="nav-number">2.5.</span> <span class="nav-text">注意</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%90%86%E8%A7%A3load%E5%92%8Cinitialize/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="iOS开发之理解load和initialize | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS开发之理解load和initialize
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-10 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-10T00:00:00+08:00">2018-04-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:13:16" itemprop="dateModified" datetime="2018-07-01T16:13:16+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="load"><a href="#load" class="headerlink" title="load"></a>load</h2><p>load 会在类装载的时候调用（main函数执行之前）。load 不会被覆盖，如果父类、父类分类、子类、子类分类，同时实现了 load 方法，那么这些方法都会执行。</p>
<h3 id="调用顺序"><a href="#调用顺序" class="headerlink" title="调用顺序"></a>调用顺序</h3><p>1、先调用父类的 load 方法，再调用子类的 load 方法。<br>2、先调用本类的 load 方法，再调用分类的 load 方法。</p>
<h3 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h3><p>1、Method Swizzle 。</p>
<h2 id="initialize"><a href="#initialize" class="headerlink" title="initialize"></a>initialize</h2><p>initialize 会在第一次给该类发送消息之前调用，有些文章说是在实例化、初始化之前调用是错的。看看文档是怎么说的</p>
<blockquote>
<p><strong>Initializes the class before it receives its first message.</strong>   </p>
</blockquote>
<h3 id="调用顺序-1"><a href="#调用顺序-1" class="headerlink" title="调用顺序"></a>调用顺序</h3><p>父类优先于子类调用 initialize 方法。<br>如果子类以及子类的分类没有实现 initialize 方法，那么当第一次给子类发消息的时候，会先给父类的 initialize 发消息。也就是父类的 initialize 方法可能会被调用多次。<br>如果本类以及其分类都实现 initialize 方法，那么只会调用 分类的 initialize 方法。</p>
<h3 id="线程安全"><a href="#线程安全" class="headerlink" title="线程安全"></a>线程安全</h3><p>initialize 是线程安全的，自带锁，当第一个线程给这个类发了 initialize 消息，其他想给这个类发 initialize 消息的线程会被阻塞，直到第一个线程发送完 initialize 消息。</p>
<h3 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h3><p><strong>1、如果本类以及本类的多个分类都实现了 initialize 方法，怎么调用？</strong><br>答：会调用 Compile Source 中的本类最后一个分类的 initialize 方法，如下图：<br><img src="http://ovsbvt5li.bkt.clouddn.com/18-4-11/38950580.jpg"><br>我在代码中实现三个 initialize 方法。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Person</span></span><br><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Person initialize.......&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Person (Special)</span></span><br><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Person (Special) initialize.......&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Person (Special1)</span></span><br><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Person (Special1) initialize.......&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结果打印出”<strong>Person (Special1) initialize…….</strong>“。<br>当我在 Compile Source 中调换了本类两个分类的先后顺序后，则打印出”<strong>Person (Special) initialize…….</strong>“。<br>从而得出结论上面的结论，Compile Source 中本类最后一个分类的 initialize 方法将会被调用。</p>
<p><strong>2、当子类及其分类没有实现 initialize 方法，在父类的 initialize 方法中怎么区分这个消息是通过本类发来的还是子类发来的？</strong><br>这里我定义了两个类，Person 为父类，Student 为子类。Student 类中没有实现 initialize 方法。那么给 Student 发消息后，结果如下：   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">self</span> == [Person <span class="keyword">self</span>]) &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;本类发来的 initialize 消息。%@ - %@&quot;</span>,<span class="keyword">self</span>,[Person <span class="keyword">self</span>]);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;子类发来的 initialize 消息。%@ - %@&quot;</span>,<span class="keyword">self</span>,[Person <span class="keyword">self</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>打印结果：<br>本类发来的 initialize 消息。Person - Person<br>子类发来的 initialize 消息。Student - Person  </p>
</blockquote>
<p>既：如果是本类发送的 initialize 消息，那么 self &#x3D;&#x3D; Person。如果是子类发送过来的消息，那么 self &#x3D;&#x3D; Student。   </p>
<h3 id="使用场景-1"><a href="#使用场景-1" class="headerlink" title="使用场景"></a>使用场景</h3><p>1、初始化静态变量。</p>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><p>1、由于 initialize 使用的是阻塞的调用方式，当一个类 initialize 依赖 另一个类的 initialize 的时候，容易造成死锁，所以应该尽量避免在 initialize 中完成一些复杂的初始化工作。<br>2、应该避免问题1这样的情况出现。如果需要在本类以及分类中同时实现初始化，可以考虑用 load 方法。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/load/" rel="tag"># load</a>
              <a href="/tags/initialize/" rel="tag"># initialize</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/04/2018/04/%5B%E7%AE%97%E6%B3%95%5D%E7%BB%99%E5%AE%9A%E5%B7%B2%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%EF%BC%8C%E6%89%BE%E5%87%BA%E5%92%8C%E4%B8%BA%E7%89%B9%E5%AE%9A%E6%95%B0%E5%80%BC%E7%9A%84%E4%B8%A4%E4%B8%AA%E6%95%B0/" rel="prev" title="给定已排序数组，找出和为特定数值的两个数">
                  <i class="fa fa-chevron-left"></i> 给定已排序数组，找出和为特定数值的两个数
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BC%96%E8%AF%91%E6%97%B6%E4%B8%8E%E8%BF%90%E8%A1%8C%E6%97%B6/" rel="next" title="iOS基础之编译时与运行时">
                  iOS基础之编译时与运行时 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
